package logic

import (
	"box-fresh/boxrpc/boxrpc"
	"box-fresh/boxrpc/internal/svc"
	"box-fresh/models/mysql"
	"context"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品创建的方法
func (l *GoodsAddLogic) GoodsAdd(in *boxrpc.GoodsAddRequest) (*boxrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	var class mysql.Class
	tx := mysql.DB.Begin()
	class.ClassGroupByName(tx, in.ClassName)
	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err := class.ClassAdd(tx)
		if err != nil {
			tx.Rollback()
			return nil, errors.New("商品类型创建失败")
		}
	}
	//商品查重
	var freshShow mysql.Fresh
	err := freshShow.FreshShow(tx, in.Name)
	if err == nil {
		tx.Rollback()
		return nil, errors.New("该商品已存在，请勿重复添加")
	}
	//单纯的商品添加+与类型表的id联立

	fresh := mysql.Fresh{
		Name:    in.Name,
		Price:   in.Price,
		Image:   in.Image,
		TypesId: int64(class.ID),
	}
	err = fresh.FreshAdd(tx)
	if err != nil {
		tx.Rollback()
		return nil, errors.New("商品添加失败")
	}
	tx.Commit()
	return &boxrpc.GoodsAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
